package com.xch.dao.impl;

import com.xch.bean.Express;
import com.xch.dao.BaseExpressDao;
import com.xch.exception.DuplicateCodeException;
import com.xch.util.DruidUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExpressDaoMysql implements BaseExpressDao {


    public static final String SQL_CONSOLE = "SELECT "+
             "COUNT(ID) data1_size, " +
             "COUNT(TO_DAYS(INTTIME)=TO_DAYS(NOW()) OR NULL) data1_day, " +
             "COUNT(STATUS=0 OR NULL) data2_size, " +
             "COUNT(TO_DAYS(INTTIME)=TO_DAYS(NOW()) AND STATUS=0 OR NULL) data2_day " +
             " FROM EXPRESS";
     public static final String SQL_FIND_ALL = "SELECT * FROM EXPRESS";
     public static final String SQL_FIND_LIMIT = "SELECT * FROM EXPRESS LIMIT ?,?";
     public static final String SQL_FIND_BY_CODE = "SELECT * FROM EXPRESS WHERE CODE=?";
     public static final String SQL_FIND_BY_NUMBER = "SELECT * FROM EXPRESS WHERE NUMBER=?";
     public static final String SQL_FIND_BY_SYSPHONE = "SELECT * FROM EXPRESS WHERE SYSPHONE=?";
     public static final String SQL_FIND_BY_USERPHONE = "SELECT * FROM EXPRESS WHERE USERPHONE=?";
     public static final String SQL_FIND_BY_USERPHONE_AND_STATUS = "SELECT * FROM EXPRESS WHERE USERPHONE=? and STATUS=?";
     public static final String SQL_INSERT = "INSERT INTO EXPRESS (NUMBER,USERNAME,USERPHONE,COMPANY,CODE,INTTIME,STATUS,SYSPHONE) VALUES(?,?,?,?,?,NOW(),0,?)";
     public static final String SQL_UPDATE = "UPDATE EXPRESS SET NUMBER=?,USERNAME=?,COMPANY=?,STATUS=? WHERE ID=?";
     public static final String SQL_UPDATE_STATUS = "UPDATE EXPRESS SET STATUS=1,OUTTIME=NOW(),CODE=NULL WHERE CODE=?";
     public static final String SQL_DELETE = "DELETE FROM EXPRESS WHERE ID=?";

    /**
     * 用于查询数据库中的全部快递（总数+新增），待取件快递（总数+新增）
     *
     * @return [{size:总数,day:新增},{size:总数,day:新增}]
     */
    @Override
    public List<Map<String, Integer>> console() {
        ArrayList<Map<String,Integer>> data = new ArrayList();
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_CONSOLE);
            //3.填充参数（可选）
            //4.执行sql语句
            result = state.executeQuery();
            //5.获取执行的结果
            if(result.next()){
                int data1_size = result.getInt("data1_size");
                int data1_day = result.getInt("data1_day");
                int data2_size = result.getInt("data2_size");
                int data2_day = result.getInt("data2_day");
                Map data1 = new HashMap();
                data1.put("data1_size",data1_size);
                data1.put("data1_day",data1_day);
                Map data2 = new HashMap();
                data2.put("data2_size",data2_size);
                data2.put("data2_day",data2_day);
                data.add(data1);
                data.add(data2);
            }
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }

    /**
     * 用于查询所有快递
     *
     * @param limit      是否分页标记，true 分页，false 不分页 查询所有快递
     * @param offset     sql语句的起始索引
     * @param pageNumber 每页查询数量
     * @return 快递集合
     */
    @Override
    public List<Express> findAll(boolean limit, int offset, int pageNumber) {
        ArrayList<Express> data = new ArrayList<>();
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            if(limit){
                state = conn.prepareStatement(SQL_FIND_LIMIT);
                //3.填充参数（可选）
                state.setInt(1,offset);
                state.setInt(2,pageNumber);
            }else{
                state = conn.prepareStatement(SQL_FIND_ALL);
            }
            //4.执行sql语句
            result = state.executeQuery();
            //5.获取执行的结果
            while(result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String userName = result.getString("username");
                String userPhone = result.getString("userphone");
                String company = result.getString("company");
                String code = result.getString("code");
                Timestamp inTime = result.getTimestamp("inttime");
                Timestamp outTime = result.getTimestamp("outtime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysphone");
                Express e = new Express(id,number,userName,userPhone,company,code,inTime,outTime,status,sysPhone);
                data.add(e);
            }
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }

    /**
     * 根据快递单号查询快递信息
     *
     * @param number 单号
     * @return 快递信息，不存在时，返回null
     */
    @Override
    public Express findByNumber(String number) {
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_FIND_BY_NUMBER);
            //3.填充参数（可选）
            state.setString(1,number);
            //4.执行sql语句
            result = state.executeQuery();
            //5.获取执行的结果
            if(result.next()){
                int id = result.getInt("id");
                String username = result.getString("username");
                String userPhone = result.getString("userphone");
                String company = result.getString("company");
                String code = result.getString("code");
                Timestamp inTime = result.getTimestamp("inttime");
                Timestamp outTime = result.getTimestamp("outtime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysphone");
                Express e = new Express(id,number,username,userPhone,company,code,inTime,outTime,status,sysPhone);
                return e;
            }
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }

    /**
     * 根据快递取件码查询快递信息
     *
     * @param code 取件码
     * @return 快递信息，不存在时，返回null
     */
    @Override
    public Express findByCode(String code) {
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_FIND_BY_CODE);
            //3.填充参数（可选）
            state.setString(1,code);
            //4.执行sql语句
            result = state.executeQuery();
            //5.获取执行的结果
            if(result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String userPhone = result.getString("userphone");
                String company = result.getString("company");
                Timestamp inTime = result.getTimestamp("inttime");
                Timestamp outTime = result.getTimestamp("outtime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysphone");
                Express e = new Express(id,number,username,userPhone,company,code,inTime,outTime,status,sysPhone);
                return e;
            }
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }

    /**
     * 根据手机号查询快递信息
     *
     * @param userPhone 取件码
     * @return 快递信息列表，不存在时，返回null
     */
    @Override
    public List<Express> findByUserPhone(String userPhone) {
        ArrayList<Express> data = new ArrayList<>();
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_FIND_BY_USERPHONE);
            //3.填充参数（可选）
            state.setString(1,userPhone);
            //4.执行sql语句
            result = state.executeQuery();
            //5.获取执行的结果
            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String company = result.getString("company");
                String code = result.getString("code");
                Timestamp inTime = result.getTimestamp("inttime");
                Timestamp outTime = result.getTimestamp("outtime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysphone");
                Express e = new Express(id,number,username,userPhone,company,code,inTime,outTime,status,sysPhone);
                data.add(e);
            }
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }

    /**
     * 根据手机号查询快递信息
     *
     * @param userPhone 取件码 status 状态
     * @param status
     * @return 快递信息列表，不存在时，返回null
     */
    @Override
    public List<Express> findByUserPhoneAndStatus(String userPhone, int status) {
        ArrayList<Express> data = new ArrayList<>();
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_FIND_BY_USERPHONE_AND_STATUS);
            //3.填充参数（可选）
            state.setString(1,userPhone);
            state.setInt(2,status);
            //4.执行sql语句
            result = state.executeQuery();
            //5.获取执行的结果
            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String company = result.getString("company");
                String code = result.getString("code");
                Timestamp inTime = result.getTimestamp("inttime");
                Timestamp outTime = result.getTimestamp("outtime");
                String sysPhone = result.getString("sysphone");
                Express e = new Express(id,number,username,userPhone,company,code,inTime,outTime,status,sysPhone);
                data.add(e);
            }
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }

    /**
     * 根据录入人手机号查询快递信息
     *
     * @param sysPhone 取件码
     * @return 快递信息列表，不存在时，返回null
     */
    @Override
    public List<Express> findBySysPhone(String sysPhone) {
        ArrayList<Express> data = new ArrayList<>();
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_FIND_BY_SYSPHONE);
            //3.填充参数（可选）
            state.setString(1,sysPhone);
            //4.执行sql语句
            result = state.executeQuery();
            //5.获取执行的结果
            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String company = result.getString("company");
                String code = result.getString("code");
                Timestamp inTime = result.getTimestamp("inttime");
                Timestamp outTime = result.getTimestamp("outtime");
                int status = result.getInt("status");
                String userPhone = result.getString("userphone");
                Express e = new Express(id,number,username,userPhone,company,code,inTime,outTime,status,sysPhone);
                data.add(e);
            }
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }

    /**
     * 快递的录入
     *INSERT INTO EXPRESS (NUMBER,USERNAME,USERPHONE,COMPANY,CODE,INTTIME,STATUS,SYSPHONE) VALUES(?,?,?,?,?,NOW(),0,?)
     * @param e 要录入的对象
     * @return 录入的结果
     */
    @Override
    public boolean insert(Express e) throws DuplicateCodeException{
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_INSERT);
            //3.填充参数（可选）
            state.setString(1, e.getNumber());
            state.setString(2, e.getUsername());
            state.setString(3, e.getUserPhone());
            state.setString(4, e.getCompany());
            state.setString(5, e.getCode());
            state.setString(6, e.getSysPhone());
            //4.执行sql语句
//            result = state.executeQuery();
            //5.获取执行的结果
            return state.executeUpdate()>0?true:false;
            //6.资源释放
        } catch (SQLException e1) {
            System.out.println(e1.getMessage());
            if(e1.getMessage().endsWith("for key 'express.code'")){
                System.out.println("取件码出现异常");
                DuplicateCodeException e2 = new DuplicateCodeException(e1.getMessage());
                throw e2;
            }else{
                e1.printStackTrace();
            }
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }

    /**
     * 快递的修改
     *
     * @param id         要修改的快递id
     * @param newExpress 要修改的快递对象(number,company,username,userPhone)
     * @return 录入的结果
     */
    @Override
    public boolean update(int id, Express newExpress) {
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_UPDATE);
            //3.填充参数（可选）
            state.setString(1, newExpress.getNumber());
            state.setString(2, newExpress.getUsername());
            state.setString(3, newExpress.getCompany());
            state.setInt(4, newExpress.getStatus());
            state.setInt(5, id);
            //4.执行sql语句
            //5.获取执行的结果
            return state.executeUpdate()>0?true:false;
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }

    /**
     * 根据id，删除单个快递信息
     *
     * @param id 要删除的快递id
     * @return 删除的结果
     */
    @Override
    public boolean delete(int id) {
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_DELETE);
            //3.填充参数（可选）
            state.setInt(1, id);
            //4.执行sql语句
            //5.获取执行的结果
            return state.executeUpdate()>0?true:false;
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }

    /**
     * 确认取件 1表示取件完成
     *
     * @param code 取件码
     * @return 取出的结果
     */
    @Override
    public boolean updateStatus(String code) {
        //1.获取数据库连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        //2.预编译sql语句
        try {
            state = conn.prepareStatement(SQL_UPDATE_STATUS);
            //3.填充参数（可选）
            state.setString(1, code);
            //4.执行sql语句
            //5.获取执行的结果
            return state.executeUpdate()>0?true:false;
            //6.资源释放
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }
}
